import axios from 'axios'
import {regularParams} from '../util/util.js'
import { message, notification } from 'ant-design-vue'
import { httpCode } from '/src/util/http'
const Base64 = require('js-base64').Base64
const qs = require('qs');
import { get, post, $delete, put, $postGetfile, $postPorm } from '@/util/http'
import { checkedAndUpload } from '@/util/minio-upload'
import { v4 as uuid } from 'uuid'

export default {
    data(){
        return {
            paramJson: {},
            globalVariableList: {},
            timer: null,
            option: {},
        }
    },
    computed:{
        isWeb(){
            return document.body.clientWidth >= 750
        },
         isH5(){
            return  750 > document.body.clientWidth
        },
        customStyle(){
            return uuid => this.isWeb ? `PC${uuid}` : `H5${uuid}`
        },
        classStyle() {
            return (uuid,item) => {
                const obj = {}
                if(uuid){
                    const classNames = JSON.parse(JSON.stringify(this.controlProperties[uuid].className))
                if (this.isWeb) {
                classNames.pcClass.reverse().forEach((item) => {                                     
                    obj[item] = true
                })
                } else {
                classNames.mClass.reverse().forEach((item) => {
                    obj[item] = true
                })
                }
                }
                if (this.controlProperties[uuid]?.calssStatusArr?.length) {
                    this.controlProperties[uuid]?.calssStatusArr.forEach((itSt) => {
                        if (item && item[itSt.key] === true) {
                        obj[itSt.identifier] = true
                        }
                    })
                }
                return obj
            }
        },
    },
    methods: {
        async $get(url, data) {
        return get(url, data)
        },
        async $post(url, data, config) {
        return post(url, data, config)
        },
        async $put(url, data) {
        return put(url, data)
        },
        async $delete(url, data) {
        return $delete(url, data)
        },
        async $postGetfile(url, data, config) {
        return $postGetfile(url, data, config)
        },
        async $postPorm(url, data, callback) {
        return $postPorm(url, data, callback)
        },
        $uuid () {
            return uuid().replace(/-/g, '')
        },
        sort(list, type) {
            if (type === 'down') {
                list.sort((a, b) => {
                    return b.dataKey.localeCompare(a.dataKey, 'zh-Hans-CN');
                })
            } else {
                list.sort((a, b) => {
                    return a.dataKey.localeCompare(b.dataKey, 'zh-Hans-CN');
                })
            }
            return list
        },
         async getGlobalValueByKey(key){
            let res = await this.$get('/queryGlobalValueByKey', {
                fieldNameKey: key,
            })
            return res.data.fieldNameValue
        },
        

        async showFn(status, $scoped,edition, aFvariable) {
            const defaultFlag=status.display==='show'
            let jude =null
            if(edition==='V1'){
             jude = await this.conditionJudge(status.displayCondition, null, $scoped)
            }else{
             jude = await this.conditionJudgeV2(status.displayCondition, $scoped, aFvariable)
            }
            const flag = defaultFlag ? !(jude && defaultFlag) : defaultFlag || jude
            return flag
        },

         base64ToArrayBuffer(base64) {
            //先解码成字符串（utf8编码表示）
            var binary_string = window.atob(base64);
            var len = binary_string.length;
            var bytes = new Uint8Array(len);
            for (var i = 0; i < len; i++) {
                //获取每个字符的实际二进制字节
                bytes[i] = binary_string.charCodeAt(i);
            }
            //实际上返回的是ArrayBuffer对象
            return bytes.buffer;
        },
        
        async UrlParse(type,list,nodeData,variableInfo){
            nodeData[type] = {}
            list.forEach(item=>{
                nodeData[type][item] = location[item]
            })
        },
        
        async CallPhone(info){
            window.location.href ="tel:" +info.dataValue    
        },
        
        
        
        
        
        async ClearSession(){
            sessionStorage.clear();
        },
        
        async OpenUrl(info){
            const {blank,dataValue} = info
            if (blank) {
                window.location.href = dataValue;
            } else {
                window.open(dataValue, '_blank');
            }              
        },
        
        async OpenPage(info){
            const {blank,pageInputParamsList,pageUuid,transientMode} = info
            const params = {}
            pageInputParamsList?.forEach(item=>{
                params[item.dataKey] = item.dataValue
            })
            if(pageUuid==='_prevPage_'){
                this.$router.go(-1)
            }else if(pageUuid==='_nextPage_'){
                this.$router.go(1) 
            }else{
                if (blank) {
                    const routeUrl = this.$router.resolve({
                        path: `/page${pageUuid}`,
                        query: {
                            ...params,
                        },
                    })
                    window.open(window.location.origin + routeUrl.href, '_blank')
                } else {
                    this.$router.push({
                        path: `/page${pageUuid}`,
                        query: {
                            ...params,
                        },
                    })
                }
            }
        },
        
        async SetVariable(info,nodeData,actionFlowLocalIdentifier){
            info.forEach(item=>{
               if(item.type==='sessionVariable'){
                    sessionStorage.setItem(item.variableUuid,item.dataValue)
               }else if(item.type==='actionFlowVariable'){
                    actionFlowLocalIdentifier[item.variableUuid] = item.dataValue
               } else if(item.type==='pageVariable'){
                this.pageLocalVariables[item.variableUuid] = item.dataValue
               }
            })
        },
        
        async  GetLocationMapLoader(key, dataKey) {
            return new Promise((resolve, reject) => {
                if (window.AMap) {
                    resolve(window.AMap)
                } else {
                    var url = `https://webapi.amap.com/maps?v=1.4.15&key=${key}&callback=onLoad${dataKey}`
                    var script = document.createElement('script')
                    script.charset = 'utf-8'
                    script.src = url
                    script.onerror = reject
                    document.head.appendChild(script)
                }
                window[`onLoad${dataKey}`] = () => {
                    resolve(window.AMap)
                }
            })
        },
        
        async RefreshDataSource(list){
            list.forEach(item=>{
                this[`getAggregate${item}`]();
            })
        },
        
        async ChangeStyle(list){
            list.forEach(item=>{
                if(this.isWeb){
                    this.controlProperties[`${item.uuid}`].className.pcClass=item.styleList
                }else{
                    this.controlProperties[`${item.uuid}`].className.mClass=item.styleList
                }
     
             })
        },
        
        async ParseJson(key,info,nodeData){
            const {ParseJson,dataType} = info
            let response =''
            if(dataType==='String'){
                response = ParseJson.analysisContent
            }else{
                try{
                    response = JSON.parse(ParseJson.analysisContent)
                    if(dataType==='List'){
                        response = [response]
                    }
                }catch(e){
                    this.$message.error('JSON格式不正确')
                }
            }
            nodeData[key] = response
        },
        
        async HTTPRequest(key,info,nodeData,globalVariableList) {
            console.log(info)
            let baseURL =info.methodUrl
            const instance = axios.create({
                timeout: info.timeout, // 设置超时时间
                baseURL,
            })
            
            if (info.queryParams && info.queryParams.length > 0) {
                const queryParams = {}
                for (let index = 0; index < info.queryParams.length; index++) {
                    const element = info.queryParams[index]
                    queryParams[element.dataKey] = element.dataValue
                }
                let params = ''
                for (let i in queryParams) {
                    params += `${i}=${queryParams[i]}&&`
                }
                params = params.slice(0, params.length - 2)
                baseURL = `${baseURL}?${params}`
            }

             // 身份认证
             let headers = {}
            if (info.authorizationType !== 1) {
                // API Key
                if (info.authorizationType === 2) {
                    const authApiKey = info.authorizationSet.params.find((v) => v.dataKey === 'key').dataValue
                    const authApiValue = info.authorizationSet.params.find((v) => v.dataKey === 'value').dataValue
                    // API Key 位置为Header
                    if (info.authorizationSet.addTo === 1) {
                        headers[`${authApiKey}`] = authApiValue
                    } else if (info.authorizationSet.addTo === 2) {
                    // API Key 位置为Query Params
                        baseURL = `${baseURL}?${authApiKey}=${authApiValue}`
                    }
                } else {
                    let authorization
                    // Bearer Token
                    if (info.authorizationType === 3) {
                        const authToken = info.authorizationSet.params.find((v) => v.dataKey === 'token').dataValue
                        authorization = `Bearer ${authToken}`
                    } else if (info.authorizationType === 4) {
                        // Basic Auth
                        const authAccount = info.authorizationSet.params.find((v) => v.dataKey === 'username').dataValue
                        const authPassword = info.authorizationSet.params.find((v) => v.dataKey === 'password').dataValue
                        const value = `${authAccount}:${authPassword}`
                        authorization = `Basic ${Base64.encode(value)}`
                    }
                    headers['authorization'] = authorization
                }
            }
            
            const headersList = info.headers
            for (let index = 0; index < headersList.length; index++) {
                const element = headersList[index]
                headers[element.dataKey] = element.dataValue
            }
            const method = info.requestMethod
            
            const contentType = info.contentType
            const params = info.bodyParams
            let formData
            //   1 ： form-data
            //   2 ：json
            //   3: none
            //   4: x-www-form-urlencoded
            //   5: raw
            if (contentType !== 3) {
                // none
                if (contentType === 1) {
                    // form-data
                    headers['Content-Type'] = 'multipart/form-data;charset=utf-8'
                    formData = new FormData()
                    for (let i = 0; i < params.length; i++) {
                        const item = params[i]
                        formData.append(item.dataKey, item.dataValue)
                    }
                } else if (contentType === 4) {
                    // x-www-form-urlencoded
                    formData = {}
                    for (let n = 0; n < params.length; n++) {
                        const nItem = params[n]
                        formData[nItem.dataKey] = nItem.dataValue
                    }
                    formData = qs.stringify(formData)
                    headers['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8'
                } else if (contentType === 5) {
                    const rawType = info.rawType
                    const rawFormatType = {
                        1: 'text/plain',
                        2: 'application/javascript',
                        3: 'application/json',
                        4: 'text/html',
                        5: 'application/xml',
                    }
                    const requestBody = info.requestBody
                    formData = requestBody
                    console.log(formData, '====', rawFormatType[rawType])
                    headers['Content-Type'] = rawFormatType[rawType]
                } else if (contentType === 2) {
                    formData = {};
                    headers['Content-Type'] = 'application/json;';
                    const getParamsDataKey=(params, nodeData, globalVariableList, paramsNew, type)=> {
                        for (let index = 0; index < params.length; index++) {
                            const element = params[index];
                            if (['Object', 'List'].includes(element.dataType) && !type) {
                                paramsNew[element.dataKey] = element.dataType === 'Object' ? {} : [{}];
                                if (element.children && element.children.length > 0) {
                                    getParamsDataKey(element.children, nodeData, globalVariableList, paramsNew[element.dataKey], element.dataType === 'Object' ? null : 'isList');
                                }
                            } else {
                                if (type === 'isList') {
                                    if (element.dataType !== 'Object') {
                                        paramsNew[0][element.dataKey] =element.dataValue
                                    } else {
                                        if (element.children && element.children.length > 0) {
                                            getParamsDataKey(element.children, nodeData, globalVariableList, paramsNew, element.dataType === 'Object' ? 'isObj' : 'isList');
                                        }
                                    }
                                } else if (type === 'isObj') {
                                    paramsNew[0][element.dataKey] = element.dataValue
                                } else {
                                    paramsNew[element.dataKey] = element.dataValue
                                }
                            }
                        }
                        return paramsNew
                    }
                   formData= getParamsDataKey(params, nodeData, globalVariableList, formData, null)
                }
            }
             const request = (data) => {
            // 请求
            let bodydata = ''

            if (['get', 'GET'].includes(method)) {
                bodydata = { params: { ...data } }
            } else {
                bodydata = { data }
            }
            return new Promise((resolve, reject) => {
                console.log(headers, '9999', method)
                instance({
                headers,
                method,
                url: baseURL,
                ...bodydata,
                })
                .then((response) => {
                    resolve(response)
                })
                .catch((error) => {
                    nodeData[key] = JSON.parse(JSON.stringify(error.response.data))
                    reject(error)
                })
            })
            }
            let _resultObj_ = await request(formData)
            nodeData[key] = JSON.parse(JSON.stringify(_resultObj_.data))
        },
        
        async ConstructJson(key,info,nodeData,type) {
            let bindParam = {}
            const setBingParams = (arr,obj)=>{
            arr.forEach(item=>{
                if(item.dataType==='Object'){
                    obj[item.dataKey] = {}
                }else if(item.dataType==='List'){
                    obj[item.dataKey] = item.dataValue?[item.dataValue]:[]
                }else {
                    item.dataKey? obj[item.dataKey] = item.dataValue:obj.push(item.dataValue)
                }
                if(item.children&&item.children.length>0){
                    if(item?.subDataDetail==='Object'){
                        item.children.forEach((v,i)=>{
                            obj[item.dataKey][i] = {}
                            setBingParams([v], obj[item.dataKey][i])
                        })
                    }else{
                        setBingParams(item.children,obj[item.dataKey],item?.subDataDetail==='Object')
                    }
                }
            })
            }
            const setSort = (obj,number)=>{
                const arr = Object.keys(obj).sort((a,b)=>{
                    return  number? a - b : b - a
                })
                let newObj = {}
                arr.forEach(key=>{
                    newObj[key] = obj[key]
                })
                return newObj
            }
            setBingParams(info.bindParam,bindParam)
            if(info.sortRule === '2'){
                bindParam = setSort(bindParam,true)
            }else if(info.sortRule ==='3'){
                bindParam = setSort(bindParam,false)
            }
            if(type==='String') bindParam = JSON.stringify(bindParam)
            nodeData[key] = bindParam
        },
        
        async DownloadFile(){
            const fileIndex = res.data[fileDataKey].file.indexOf("/");
            const file = res.data[fileDataKey].file.slice(fileIndex + 1);
            var obj = window.URL.createObjectURL(
            new Blob([this.base64ToArrayBuffer(file)])
            );
            var btn = document.createElement("a");
            btn.download = res.data[fileDataKey].file.split("/")[0];
            btn.href = obj;
            document.body.appendChild(btn);
            btn.click();
            document.body.removeChild(btn);
        },

        basicCalculateImplement(expressionJs, params) {
            for (let key in params) {
                if (typeof params[key] !== 'function') {
                    if (params[key] && typeof params[key] === 'string') {
                        expressionJs = expressionJs.replaceAll(key, `'${params[key]}'`)
                    } else if (
                        params[key].constructor === Object ||
                        params[key].constructor === Array
                    ) {
                        expressionJs = expressionJs.replaceAll(
                        key,
                        JSON.stringify(params[key])
                        )
                    } else {
                        expressionJs = expressionJs.replaceAll(key, params[key])
                    }
                    } else {
                        if (params[key]() && typeof params[key]() === 'string') {
                            expressionJs = expressionJs.replaceAll(key, `'${params[key]()}'`)
                        } else if (
                            typeof params[key]() === 'object' && 
                            params[key]().constructor === Object ||
                            params[key]().constructor === Array
                        ) {
                            expressionJs = expressionJs.replaceAll(
                            key,
                            JSON.stringify(params[key]())
                            )
                    } else {
                        expressionJs = expressionJs.replaceAll(key, params[key]())
                    }
                }
            }
            const result = eval(expressionJs)
            return result
        },

        getOperationReturnResult(expressionJs, args) {
            for (let i in args) {
                window[i] = args[i]()
            }
            return eval(expressionJs)
        },

        evil(fn) {
            let Fn = Function
            return new Fn('return ' + fn)()
        },
    },
    beforeDestroy() {
        clearInterval(this.timer)
    },
}

